import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STData, STPage, STRes } from '@delon/abc/st';
import { SFComponent, SFSchema, SFSelectWidgetSchema } from '@delon/form';
import { ModalHelper, _HttpClient, SettingsService } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { ConfAccountEditComponent } from './edit/edit.component';

@Component({
  selector: 'app-conf-account',
  templateUrl: './account.component.html'
})
export class ConfAccountComponent implements OnInit {
  url = `api/accounts`;
  isAdmin = false;
  isShow = false;
  company_id = 0;
  @ViewChild('sf', { static: false }) private sf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      company_id: {
        type: 'string',
        title: '',
        readOnly: !this.isAdmin && !this.isShow,
        ui: {
          widget: 'select',
          placeholder: '所属组织',
          asyncData: () =>
            this.loadDataFromServer().pipe(
              map((value: any) => {
                //console.log(value);
                return value;
              })
            )
        } as SFSelectWidgetSchema
      },
      keyword: {
        type: 'string',
        title: '',
        ui: {
          placeholder: '关联店铺｜公司'
        }
      },
      username: {
        type: 'string',
        title: '',
        ui: {
          placeholder: '用户名'
        }
      },
      shopId: {
        type: 'string',
        title: '',
        ui: {
          placeholder: '店铺ID'
        }
      }
    }
  };
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    { title: '账户名', index: 'username', className: 'text-center' },
    { title: '关联店铺', index: 'fordeal_shop_name', className: 'text-center' },
    { title: '关联公司', index: 'shop_name', className: 'text-center', default: '-' },
    { title: '店铺ID', index: 'shop_id', className: 'text-center', default: '-' },
    {
      title: '状态',
      index: 'status',
      type: 'badge',
      badge: {
        0: { text: '禁用', color: 'error' },
        1: { text: '启用', color: 'success' }
      },
      className: 'text-center',
      colSpan: 10
    },
    { title: '所属组织', index: 'company_name', className: 'text-center', default: '-' },
    { title: '创建时间', type: 'date', index: 'CreatedAt', className: 'text-center' },
    { title: '更新时间', type: 'date', index: 'UpdatedAt', className: 'text-center' },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          icon: 'edit',
          type: 'static',
          modal: {
            component: ConfAccountEditComponent,
            params: (record: STData) => record,
            modalOptions: { nzMaskClosable: false }
          },
          click: 'reload'
        },
        { text: '删除', type: 'del', icon: 'delete', className: 'text-error', click: (item: any) => this.del(item.ID) }
      ],
      className: 'text-center'
    }
  ];

  res: STRes = {
    reName: {
      total: 'data.total',
      list: 'data.list'
    }
  };

  paginate: STPage = {
    showSize: true
  };

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msgSrv: NzMessageService,
    private settingService: SettingsService
  ) {
    this.company_id = this.settingService.user.company_id;
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
      let company_id = this.searchSchema?.properties?.company_id;
      if (company_id) {
        company_id.readOnly = false;
      }
    }

    if (!this.isAdmin) {
      // @ts-ignore
      let e = this.columns[8].buttons[1];
      e.className = 'text-error hidden-cell';
    }

    this.loadCompanies();
    //this.showHideSchemaItems();

    // this.loadDataFromServer();
  }

  showHideSchemaItems() {
    if (!this.isAdmin && this.isShow) {
      let company_id = this.searchSchema?.properties?.company_id;
      if (company_id) {
        company_id.readOnly = false;
      }
      this.searchSchema = {
        properties: {
          company_id: {
            type: 'string',
            title: '',
            readOnly: false,
            ui: {
              widget: 'select',
              placeholder: '所属组织',
              asyncData: () =>
                this.loadDataFromServer().pipe(
                  map((value: any) => {
                    //console.log(value);
                    return value;
                  })
                )
            } as SFSelectWidgetSchema
          },
          keyword: {
            type: 'string',
            title: '',
            ui: {
              placeholder: '关联店铺｜公司'
            }
          },
          username: {
            type: 'string',
            title: '',
            ui: {
              placeholder: '用户名'
            }
          },
          shopId: {
            type: 'string',
            title: '',
            ui: {
              placeholder: '店铺ID'
            }
          }
        }
      };
    }

    if (!this.isAdmin && !this.isShow) {
      this.searchSchema = {
        properties: {
          keyword: {
            type: 'string',
            title: '',
            ui: {
              placeholder: '关联店铺｜公司'
            }
          },
          username: {
            type: 'string',
            title: '',
            ui: {
              placeholder: '用户名'
            }
          },
          shopId: {
            type: 'string',
            title: '',
            ui: {
              placeholder: '店铺ID'
            }
          }
        }
      };
    }
  }

  ngOnInit = (): void => {};

  loadDataFromServer(): Observable<Array<{ label: any; value: any }>> {
    return this.http.get(`api/company_map`).pipe(
      map((resp: any) => {
        const arr: Array<{ label: any; value: any }> = [];
        const list = resp.data;
        if (list && list.length) {
          list.forEach((element: { company_name: any; ID: any }) => {
            arr.push({ label: element.company_name, value: element.ID });
          });
        }
        if (list && list.length > 1) {
          this.isShow = true;
        }

        return arr;
      })
    );
  }

  companyList = [];
  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
      if (this.companyList.length > 1) {
        //this.isShow = true;
      }
      this.showHideSchemaItems();
    });
  }

  add(): void {
    this.modal.createStatic(ConfAccountEditComponent, { i: { id: 0 } }).subscribe(() => this.st.reload());
  }

  /**
   * 删除
   *
   * @param id 数据id
   */
  del(id: number): void {
    if (!this.isAdmin) {
      this.msgSrv.warning('您没有权限进行删除操作!');
      return;
    }
    this.http.delete(`api/account/${id}`).subscribe(() => {
      this.st.reload();
    });
  }
}
